//
//  ZZLoginViewController.m
//  ZuZuBao
//
//  Created by Felix on 2024/4/8.
//

#import "ZZLoginViewController.h"
#import "ZZRegisterViewController.h"

@interface ZZLoginViewController ()

@property (nonatomic, strong) UITextField * pTxField;
@property (nonatomic, strong) UITextField * cTxField;
@property (nonatomic, strong) UIButton * codeButton;
@property (nonatomic, strong) NSTimer * codeTimer;
///倒计时
@property (nonatomic, assign) NSInteger timeCount;

@end

@implementation ZZLoginViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"";
    self.timeCount = 60;
    
    [self createView];
}

- (void)createView {
    UIImageView * bkImgVIew = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    bkImgVIew.image = [UIImage imageNamed:@"back_image"];
    [self.view addSubview:bkImgVIew];
    
    UIImageView * imgView = [[UIImageView alloc] initWithFrame:CGRectMake(53, kNavBarHeight, kScreenWidth - 53 * 2, 196)];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    imgView.image = [UIImage imageNamed:@"login_img"];
    [self.view addSubview:imgView];
    
    self.pTxField = [[UITextField alloc] initWithFrame:CGRectMake(kPadding, CGRectGetMaxY(imgView.frame) + 20, kScreenWidth - kPadding * 2, 48)];
    self.pTxField.backgroundColor = kRGBAColor(0xD9E4F3, 1);
    self.pTxField.layer.cornerRadius = 24;
    self.pTxField.layer.masksToBounds = YES;
    self.pTxField.placeholder = @"请输入手机号";
    self.pTxField.textColor = k333Color;
    self.pTxField.font = [UIFont systemFontOfSize:16];
    self.pTxField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kPadding, 48)];
    self.pTxField.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.pTxField];
    
    self.cTxField = [[UITextField alloc] initWithFrame:CGRectMake(kPadding, CGRectGetMaxY(self.pTxField.frame) + 25, kScreenWidth - kPadding * 2, 48)];
    self.cTxField.backgroundColor = kRGBAColor(0xD9E4F3, 1);
    self.cTxField.layer.cornerRadius = 24;
    self.cTxField.layer.masksToBounds = YES;
    self.cTxField.placeholder = @"请输入验证码";
    self.cTxField.textColor = k333Color;
    self.cTxField.font = [UIFont systemFontOfSize:16];
    self.cTxField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kPadding, 48)];
    self.cTxField.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.cTxField];
    
    self.codeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.codeButton.frame = CGRectMake(self.cTxField.frame.origin.x + self.cTxField.frame.size.width - 90, CGRectGetMaxY(self.pTxField.frame) + 25, 80, 48);
    [self.codeButton setTitleColor:kRGBAColor(0x127FFF, 1) forState:UIControlStateNormal];
    [self.codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.codeButton.titleLabel.font = [UIFont systemFontOfSize:14];
    self.codeButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    [self.codeButton addTarget:self action:@selector(codeAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.codeButton];
    
    UIButton * loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.frame = CGRectMake(kPadding, CGRectGetMaxY(self.cTxField.frame) + 25, kScreenWidth - kPadding * 2, 48);
    loginButton.backgroundColor = [UIColor blackColor];
    loginButton.layer.cornerRadius = 24;
    loginButton.layer.masksToBounds = YES;
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    loginButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [loginButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginButton];
    
//    UIButton * registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    registerButton.frame = CGRectMake(kPadding, CGRectGetMaxY(loginButton.frame) + 10, kScreenWidth - kPadding * 2, 34);
//    NSString *string = @"没有账号，去注册";
//    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
//    NSRange helloRange = [string rangeOfString:@"没有账号，去"];
//    [attributedString addAttribute:NSForegroundColorAttributeName
//                               value:k333Color
//                               range:helloRange];
//    NSRange worldRange = [string rangeOfString:@"注册"];
//    [attributedString addAttribute:NSForegroundColorAttributeName
//                               value:kRGBAColor(0x127FFF, 1)
//                               range:worldRange];
//    [registerButton setAttributedTitle:attributedString forState:UIControlStateNormal];
//    registerButton.titleLabel.font = [UIFont systemFontOfSize:14];
//    [registerButton addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:registerButton];

}

- (void)codeAction {
    if (self.pTxField.text.length == 0) {
        [MBProgressHUD showMessage:@"请输入手机号" toView:self.view];
        return;
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", kBaseUrl, kSendSms];
    NSDictionary *params = @{@"phone": [NSString stringWithFormat:@"%@", self.pTxField.text],
                                 @"type" : @(1)
                                 };
    
    [kFFNetManager POST:urlString parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject:~~~%@", responseObject);
        if ([responseObject[@"code"] integerValue] == 200) {
            [self.codeTimer invalidate];
            self.codeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(codeCountAction) userInfo:nil repeats:YES];
            [self.codeTimer fire];
            [MBProgressHUD showMessage:@"验证码已发送" toView:self.view];
        }else {
             
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

//倒计时
- (void)codeCountAction
{
    self.timeCount--;
    if (self.timeCount == 0) {
        [self.codeTimer invalidate];
        self.codeTimer = nil;
        [self.codeButton setTitleColor:kRGBAColor(0x127FFF, 1) forState:UIControlStateNormal];
        [self.codeButton setTitle:@"发送验证码" forState:UIControlStateNormal];
        self.codeButton.userInteractionEnabled = YES;
        self.timeCount = 60;
    } else {
        [self.codeButton setTitleColor:k999Color forState:UIControlStateNormal];
        [self.codeButton setTitle:[NSString stringWithFormat:@"已发送%ld(s)",(long)self.timeCount] forState:UIControlStateNormal];
        self.codeButton.userInteractionEnabled = NO;
    }
}

- (void)loginAction {

    if (self.pTxField.text.length == 0) {
        [MBProgressHUD showMessage:@"请输入手机号" toView:self.view];
        return;
    }
    if (self.cTxField.text.length == 0) {
        [MBProgressHUD showMessage:@"请输入验证码" toView:self.view];
        return;
    }

    NSString *urlString = [NSString stringWithFormat:@"%@%@", kBaseUrl, kLogin];
    NSDictionary *params = @{@"mobile": self.pTxField.text,
                                 @"smsCode": self.cTxField.text
                                 };
    
    [kFFNetManager POST:urlString parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject:~~~%@", responseObject);
        if ([responseObject[@"code"] integerValue] == 200) {
            NSDictionary * reponseDic = responseObject[@"result"];
            ZZUserModel * model = [[ZZUserModel alloc] init];
            model = [ZZUserModel mj_objectWithKeyValues:reponseDic];
            kUid = [NSString stringWithFormat:@"%ld", model.uid];
            kNickName = model.nickName;
            kHeadImg = model.headImg;
            kToken = model.token;
            kPhone = self.pTxField.text;
            if (self.block) {
                self.block();
            }

            [MBProgressHUD showMessage:@"登录成功" toView:self.view];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
             
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
    
}

- (void)registerAction {
    ZZRegisterViewController * vc = [[ZZRegisterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
